package com.zyk.problem;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * n个线程合作输出
 *
 * @author zhangsan
 * @date 2021/5/6 14:12
 */
public class NThreadsCooperate {

    static class Right {

        AtomicInteger cnt;
        Thread[] threads;
        char[] str = new char[26];
        int n;

        public Right(int n) {
            this.n = n;
            for (int i = 0; i < 26; i++) {
                str[i] = (char) ('A' + i);
            }
            cnt = new AtomicInteger(-1);
            threads = new Thread[n];
            for (int i = 0; i < n; i++) {
                threads[i] = new Thread(new Task(i), ("thread" + i));
                threads[i].start();
            }
            LockSupport.unpark(threads[0]);
        }

        class Task implements Runnable {

            int id;

            public Task(int id) {
                this.id = id;
            }

            @Override
            public void run() {
                LockSupport.park();
                while (cnt.get() < 25) {
                    System.out.println(Thread.currentThread() + ": " + str[cnt.incrementAndGet()]);
                    LockSupport.unpark(threads[id + 1 == n ? 0 : id + 1]);
                    LockSupport.park();
                }
                System.exit(0);
            }
        }
    }

    static class Right2 {

        Lock lock = new ReentrantLock();

        public void print() {
            Condition condition = lock.newCondition();
//            condition.await();
//            condition.signal();
        }

    }


    public static void main(String[] args) {
        int n = 3;
        new Right(n);
    }

}
